//
//  LoginViewController.m
//  tuanGG
//
//  Created by 微他 on 15/9/25.
//  Copyright (c) 2015年 weita. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisteredViewController.h"
#import "ModifyPasswordViewController.h"
#import "Header.h"
#import "UserInfo.h"
#import "TabBarController.h"
#import "CustomAlertView.h"
static LoginViewController * login = nil;
@interface LoginViewController ()<UIAlertViewDelegate>
{
    UIImageView * _loginImage;
    UIView * _phoneleftView;
    UIView * _pswleftView;
    UITapGestureRecognizer * _forgetTap;
}

//登录
@property (nonatomic,strong)UIButton * loginSureBtn;
//忘记密码
@property (nonatomic,strong)UILabel * forgetPsw;
//注册
@property (nonatomic,strong)UIButton * registerBtn;

@property (nonatomic,strong)NSMutableDictionary * versionDic;
@property (nonatomic,strong)NSString * downloadVersion;//新版本下载地址
@end

@implementation LoginViewController
+ (id)sharedLoginControl {
    if (!login) {
        login = [[LoginViewController alloc]init];
    }
    return login;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.frame = CGRectMake(0, -64, ScreenWidth, 64);
    self.view.backgroundColor = RGBACOLOR(236, 235, 232, 1);
    [self initNav];
    [self lqkinLoginInit];
}
- (void)initNav {
    UIView *nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, self.navigationController.navigationBar.frame.size.height)];
    UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, nav.frame.size.height-35, 30, 30)];
    [backButton setImage:IMGNAME(@"back") forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButton) forControlEvents:UIControlEventTouchUpInside];
    nav.backgroundColor = [UIColor colorWithHexString:@"4fd2be"];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, nav.frame.size.height-30, ScreenWidth, 20)];
    label.text = @"登录";
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:font_Font size:20];
    label.textAlignment = NSTextAlignmentCenter;
    [nav addSubview:label];
    [nav addSubview:backButton];
    [self.view addSubview:nav];
}
- (void)backButton {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
- (void)lqkinLoginInit
{
//    [self.navigationItem setHidesBackButton:YES animated:NO];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyloginout:) name:@"loginout" object:nil];
    
    self.view.userInteractionEnabled = YES;
    _loginImage = [[UIImageView alloc]initWithFrame:CGRectMake(117*PRO, self.navigationController.navigationBar.frame.size.height+30, 84, 84)];
    _loginImage.image = IMGNAME(@"title.png");
    [self.view addSubview:_loginImage];
    
    
    UIView * loginView = [[UIView alloc]initWithFrame:CGRectMake(15,CGRectGetMaxY(_loginImage.bounds) + 32 + 35+60, ScreenWidth - 30, 90)];
    [loginView.layer setCornerRadius:5.0];
    loginView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:loginView];
    
    //账号
    _phoneTxt = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth - 30, 45)];
    _phoneTxt.placeholder = @"请输入手机号码";
    _phoneTxt.clearButtonMode = UITextFieldViewModeWhileEditing;
    _phoneTxt.font = BOLD_FONT(12);
    _phoneTxt.text = @"";
    _phoneTxt.keyboardType = UIKeyboardTypeNumberPad;
    [loginView addSubview:_phoneTxt];
    
    
    _phoneleftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 35, 45)];
    [self.view addSubview:_phoneleftView];
    UIImageView * phoneleft = [[UIImageView alloc]initWithFrame:CGRectMake(10, 13.5*PRO, 17, 18)];
    phoneleft.image = [UIImage imageNamed:@"AcountLeftimage.png"];
    [_phoneleftView addSubview:phoneleft];
    _phoneTxt.leftViewMode = UITextFieldViewModeAlways;
    _phoneTxt.leftView = _phoneleftView;
    
    
    
    //密码
    _pswTxt = [[UITextField alloc]initWithFrame:CGRectMake(0, 45, ScreenWidth - 30, 45)];
    _pswTxt.placeholder = @"请输入密码";
    _pswTxt.clearButtonMode = UITextFieldViewModeWhileEditing;
    _pswTxt.font = BOLD_FONT(12);
    _pswTxt.secureTextEntry = YES;
    _pswTxt.text  = @"";
    [loginView addSubview:_pswTxt];
    
    
    _pswleftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 35, 45)];
    UIImageView *pswleft = [[UIImageView alloc]initWithFrame:CGRectMake(10, 12*PRO, 15, 19)];
    pswleft.image = [UIImage imageNamed:@"authCodeLeftimage.png"];
    [_pswleftView addSubview:pswleft];
    _pswTxt.leftViewMode = UITextFieldViewModeAlways;
    _pswTxt.leftView = _pswleftView;
    
    
    //分割线
    UIView * lineView = [[UIView alloc ]initWithFrame:CGRectMake(0, 45, ScreenWidth-30, 0.6)];
    lineView.backgroundColor = [UIColor colorWithHexString:@"c8c8c8" alpha:0.5];
    [loginView addSubview:lineView];
    
    //登录按钮
    _loginSureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginSureBtn.frame = CGRectMake(15, CGRectGetMaxY(_loginImage.bounds) + 148 + 35+60, ScreenWidth - 30, 40);
    _loginSureBtn.backgroundColor = [UIColor colorWithHexString:@"33ccbf"];
    _loginSureBtn.titleLabel.font = BOLD_FONT(15);
    [_loginSureBtn setTitle:@"登录" forState:UIControlStateNormal];
    [_loginSureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_loginSureBtn.layer setCornerRadius:5.0];
    [_loginSureBtn addTarget:self action:@selector(processBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _loginSureBtn.tag = 200;
    [self.view addSubview:_loginSureBtn];
    
    //忘记密码
    _forgetPsw = [[UILabel alloc]init];
    if (iPhone4s) {
        _forgetPsw.frame = CGRectMake(ScreenWidth - 135, CGRectGetMaxY(_loginImage.bounds) + 128 + 35 + 64+60, 120, 30);
    }
    else
    {
        _forgetPsw.frame = CGRectMake(ScreenWidth - 135, CGRectGetMaxY(_loginImage.bounds) + 148 + 35 + 64+60, 120, 30);
    }
    
    _forgetPsw.text = @"忘记/修改密码";
    _forgetPsw.textColor = [UIColor colorWithHexString:@"33ccbf"];
    _forgetPsw.tag = 201;
    _forgetPsw.font = [UIFont systemFontOfSize:15];
    _forgetPsw.textAlignment = NSTextAlignmentRight;
    //    [_forgetPsw sizeToFit];
    _forgetPsw.userInteractionEnabled = YES;
    
    [self.view addSubview:_forgetPsw];
    //    _forgetPsw.layer.borderWidth = 1;
    _forgetTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(forgetPswTap)];
    
    [_forgetPsw addGestureRecognizer:_forgetTap];
    
    //注册
    _registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _registerBtn.frame = CGRectMake(15, ScreenHeight - 18 - 44, ScreenWidth - 30, 40);
    _registerBtn.backgroundColor = [UIColor whiteColor];
    [_registerBtn setTitle:@"注册成为商家" forState:UIControlStateNormal];
    [_registerBtn setTitleColor:[UIColor colorWithHexString:@"33ccbf"] forState:UIControlStateNormal];
    [_registerBtn addTarget:self action:@selector(processBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _registerBtn.tag = 202;
    _registerBtn.titleLabel.font = BOLD_FONT(15);
    [self.view addSubview:_registerBtn];
    
    
    //版本更新
    //版本更新
//        _versionDic = [NSMutableDictionary dictionary];
//        NSString * key = PLIST_version;
//        _versionDic = [[NSMutableDictionary alloc]initWithContentsOfFile:key];
//    
//        [self VersionUpdateNetWorking];
//    
//        BaseVerSion * baseVerSion = [[BaseVerSion alloc]init];
//    
//        [baseVerSion VersionUpdateNetWorkingWithURL:version_url];
}



- (void)VersionUpdateNetWorking
{
//    NSMutableDictionary * params = [NSMutableDictionary dictionary];
//    [GLAFRequest startRequest:version_url paramsDic:params defaultdialog:NO ispost:NO handleSuccess:^(id sta, NSDictionary *paramsDic) {
//        
//        if ([sta[@"code"] integerValue] == 1) {
//            
//            if ([sta[@"newversion"] count] > 0) {
//                
//                NSString * verSion = [NSString stringWithFormat:@"新版本:%@是否需要更新?,当前版本:%@",sta[@"newversion"][@"versionnum"],_versionDic[@"CFBundleShortVersionString"]];
//                _downloadVersion = [NSString stringWithString:sta[@"newversion"][@"download"]];
//                //当前有新版本需要更新
//                [CustomAlertView alterMsg:verSion delegate:self];
//                return ;
//            }
//            
//        }
//        
//    } doFinally:^(NSDictionary *paramsDic) {
//        
//        
//    } netWorkFail:^(NSDictionary *paramsDic) {
//        [CustomAlertView alterSureMsg:@"网络连接异常,请检查网络连接" delegate:nil];
//        
//    }];
}

#pragma mark - <UIAlertViewDelegate版本下载提示代理>
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        //        @"http://www.baidu.com"
        //        _downloadVersion
        //        NSString * url =  @"http://www.baidu.com";
        NSString * url =  _downloadVersion;
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }
}

//
- (void)processBtnClick:(UIButton *)sender
{

    switch (sender.tag - 200) {
        case 0:
            //登录按钮
            [self login];
            break;
        case 1:
            //忘记密码
            [self forgetPswTap];
            break;
        case 2:
            //注册
            [self registerBs];
            break;
        default:
            break;
    }
}

- (void)login
{
    [self.view endEditing:YES];
    //    self.phoneTxt.text = @"18108036732";
    //    self.pswTxt.text = @"111111";
    [self delectedTxtIsnull];
}
- (void)registerBs
{
    RegisteredViewController * RegisteredVC = [[RegisteredViewController alloc]init];
    RegisteredVC.index = 10;
    [self.navigationController pushViewController:RegisteredVC animated:YES];
}

#pragma mark - <忘记密码>
- (void)forgetPswTap
{
    ModifyPasswordViewController * PasswordVC = [[ModifyPasswordViewController alloc]init];
    [self.navigationController pushViewController:PasswordVC animated:YES];
    
}
//#pragma mark - <UIBarButtonItemClick>
//- (void)leftBarloginBackButtonClick:(UIBarButtonItem *)item
//{
//        [self dismissViewControllerAnimated:YES completion:nil];
//    if ([UserInfo sharedUserInfo].loginStatus) {
//        [self.navigationController popViewControllerAnimated:YES];
//    }
//    else
//    {
//        LoginViewController * loiginvc = [[LoginViewController alloc]init];
//        [self.navigationController pushViewController:loiginvc animated:YES];
//        self.navigationController.navigationItem.leftBarButtonItem = nil;
//    }
//
//}


- (void)setPlacedholderFontWithstring:(NSString *)placedholderStr textField:(UITextField *)textField font:(CGFloat)font
{
//    NSMutableAttributedString * attributedStr = [[NSMutableAttributedString alloc]initWithString:placedholderStr];
//    [attributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font] range:NSMakeRange(0, attributedStr.length)];
//    textField.textAlignment = NSTextAlignmentLeft;
//    
//    textField.attributedPlaceholder = attributedStr;
}
- (void)drawPlaceholderInRect:(CGRect)rect textfield:(UITextField *)textField
{
//    //CGContextRef context = UIGraphicsGetCurrentContext();
//    //CGContextSetFillColorWithColor(context, [UIColor yellowColor].CGColor);
//    //    [[UIColororangeColor] setFill];
//    
//    [[textField placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:20]];
}


#pragma makr - <判断字段是否为空>
- (void)delectedTxtIsnull
{
    if ([_phoneTxt.text isEqualToString:@""]) {
        [self addAlert:@"请输入手机号码" otherButtonTitles:nil];
    }
    else
    {
        
        if (![ValidateMobileWithEmail validateMobile:_phoneTxt.text]) {
            [self addAlert:@"手机号码格式不正确" otherButtonTitles:nil];
            
        }
        else
        {
            if ([_pswTxt.text isEqualToString:@""]) {

                [self addAlert:@"请输入密码" otherButtonTitles:nil];

            }
            else
            {
                if (_pswTxt.text.length < 6)
                {

                    [self addAlert:@"请输入6-16位的密码" otherButtonTitles:nil];
                }
                else
                {
                    //登录成功
//                    TabBarController *tabBar = [[TabBarController alloc]init];
//                    [self.navigationController presentViewController:tabBar animated:YES completion:nil];
                    [self lqkinloginSucess];
                    
                }
            }
        }
        
    }
}




#pragma mark - <登录网络请求>
- (void)lqkinloginSucess
{

    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:self.phoneTxt.text forKey:@"tel"];
    [params setObject:[Common md5HexDigest:self.pswTxt.text] forKey:@"psw"];
    [GLAFRequest startRequest:[NSString stringWithFormat:@"%@%@",baseurl_url,login_url] defaultdialog:YES paramsDic:params handleSuccess:^(id sta, NSDictionary *paramsDic) {
        
        NSLog(@"个人信息：%@",sta);
        if ([sta[@"code"] integerValue] == 1) {
            [UserInfo sharedUserInfo].loginStatus = YES;
            [UserInfo sharedUserInfo].logo = YES;
            [UserInfo sharedUserInfo].uid = [sta[@"a_memberupdateobj"][@"uid"]integerValue];
            NSLog(@"%zi",[UserInfo sharedUserInfo].uid);
            //个人信息
            [[NSUserDefaults standardUserDefaults] setObject:sta[@"a_memberupdateobj"][@"uid"] forKey:@"supe_uid"];
            [[UserInfo sharedUserInfo] saveUserInfoToSandbox];
            [UserInfo sharedUserInfo].phoneNumber = self.phoneTxt.text;
            TabBarController *tabBar = [[TabBarController alloc]init];
            [self.navigationController presentViewController:tabBar animated:YES completion:nil];

        }
        
    } netWorkFail:^(NSDictionary *paramsDic) {
        
        [CustomAlertView alterMsg:@"网络连接异常,请检查网络连接" delegate:nil];
    }];

}

//- (void)notifyloginout:(NSNotification *)notify
//{
//    [self.navigationItem setHidesBackButton:YES];
//}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}
@end
